package com.casic.common.ibatis.typeHandler;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeException;
import org.apache.ibatis.type.TypeHandler;

import java.sql.*;
import java.util.Date;


/**
 * @Company 航天科技山西公司
 * @Project hitech-Common
 * @Package com.hitech.ibatis.typeHandler
 * @ClassName DateTypeHandler.java
 * @Description TODO(DateTypeHandler)
 * @author yangying
 * @create 2016年9月21日-下午5:13:09
 */
public class DateTypeHandler implements TypeHandler<Date> {

	@Override
	public Date getResult(ResultSet arg0, String arg1) throws SQLException {
		// TODO Auto-generated method stub
	    if (arg0.wasNull()) {
	      return null;
	    } 
	    Timestamp sqlTimestamp = arg0.getTimestamp(arg1);
	    if (sqlTimestamp != null) {
	      return new Date(sqlTimestamp.getTime());
	    }
	    return null;
	}

	@Override
	public Date getResult(ResultSet arg0, int arg1) throws SQLException {
		// TODO Auto-generated method stub
	    if (arg0.wasNull()) {
	      return null;
	    } 
	    Timestamp sqlTimestamp = arg0.getTimestamp(arg1);
	    if (sqlTimestamp != null) {
	      return new Date(sqlTimestamp.getTime());
	    }
	    return null;
	}

	@Override
	public Date getResult(CallableStatement arg0, int arg1) throws SQLException {
		// TODO Auto-generated method stub
	    if (arg0.wasNull()) {
	      return null;
	    }
	    Timestamp sqlTimestamp = arg0.getTimestamp(arg1);
	    if (sqlTimestamp != null) {
	      return new Date(sqlTimestamp.getTime());
	    }
	    return null;
	}

	@Override
	public void setParameter(PreparedStatement arg0, int arg1, Date arg2,
			JdbcType arg3) throws SQLException {
		// TODO Auto-generated method stub
		if (arg2 == null) {
	      if (arg3 == null) {
	        throw new TypeException("JDBC requires that the JdbcType must be specified for all nullable parameters.");
	      }
	      try {
	    	  arg0.setNull(arg1, arg3.TYPE_CODE);
	      } catch (SQLException e) {
	        throw new TypeException("Error setting null for parameter #" + arg1 + " with JdbcType " + arg3 + " . " +
	        		"Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. " +
	        		"Cause: " + e, e);
	      }
	    } else {
	    	arg0.setTimestamp(arg1, new Timestamp((arg2).getTime()));
	    }
	}

	

  

}
